/**    
 * 文件名：WeixinXmlTool.java    
 *    
 * 版本信息：    
 * 日期：2015-7-27    
 * Copyright inspursoftware Corporation 2015     
 * 版权所有    
 *    
 */
package com.thinkgem.jeesite.common.utils.wx;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.thinkgem.jeesite.modules.config.entity.weixin.ConfigWechat;

/**    
 *     
 * 项目名称：ALM_eb_web    
 * 类名称：WeixinXmlTool    
 * 类描述：    
 * 创建人：zhaoshuhe    
 * 创建时间：2017-1-18 下午4:17:41    
 * @version     
 *     
 */
public class WeixinXmlTool {
    public static String getWeixinPayXml(Map<String, String> paramMap){
		StringBuilder xmlStr = new StringBuilder();
		xmlStr.append("<xml>")
			.append("<appid>"+paramMap.get("appid")+"</appid>")
			.append("<attach>"+paramMap.get("attach")+"</attach>")
			.append("<body>"+paramMap.get("body")+"</body>")
			.append("<detail>"+paramMap.get("detail")+"</detail>")
			.append("<mch_id>"+paramMap.get("mch_id")+"</mch_id>")
			.append("<nonce_str>"+paramMap.get("nonce_str")+"</nonce_str>")
			.append("<notify_url>"+paramMap.get("notify_url")+"</notify_url>")
			.append("<out_trade_no>"+paramMap.get("out_trade_no")+"</out_trade_no>")
			.append("<spbill_create_ip>"+paramMap.get("spbill_create_ip")+"</spbill_create_ip>")
			.append("<total_fee>"+paramMap.get("total_fee")+"</total_fee>")
			.append("<trade_type>"+paramMap.get("trade_type")+"</trade_type>")
			.append("<sign>"+paramMap.get("sign")+"</sign>")
			.append("</xml> ");
		return xmlStr.toString();
    }
    public static String getWeixinPayXmlGZ(Map<String, String> paramMap){
		StringBuilder xmlStr = new StringBuilder();
		xmlStr.append("<xml>")
			.append("<appid>"+paramMap.get("appid")+"</appid>")
			.append("<attach>"+paramMap.get("attach")+"</attach>")
			.append("<body>"+paramMap.get("body")+"</body>")
			.append("<mch_id>"+paramMap.get("mch_id")+"</mch_id>")
			.append("<nonce_str>"+paramMap.get("nonce_str")+"</nonce_str>")
			.append("<notify_url>"+paramMap.get("notify_url")+"</notify_url>")
			.append("<openid>"+paramMap.get("openId")+"</openid>")
			.append("<out_trade_no>"+paramMap.get("out_trade_no")+"</out_trade_no>")
			.append("<spbill_create_ip>"+paramMap.get("spbill_create_ip")+"</spbill_create_ip>")
			.append("<total_fee>"+paramMap.get("total_fee")+"</total_fee>")
			.append("<trade_type>"+paramMap.get("trade_type")+"</trade_type>")
			.append("<sign>"+paramMap.get("sign")+"</sign>")
			.append("</xml> ");
		return xmlStr.toString();
    }
    
    public static String getWeixinRefundXml(Map<String, String> paramMap){
		StringBuilder xmlStr = new StringBuilder();
		xmlStr.append("<xml>")
			.append("<appid>"+paramMap.get("appid")+"</appid>")
			.append("<mch_id>"+paramMap.get("mch_id")+"</mch_id>")
			.append("<nonce_str>"+paramMap.get("nonce_str")+"</nonce_str>")
			.append("<op_user_id>"+paramMap.get("op_user_id")+"</op_user_id>")
			.append("<out_refund_no>"+paramMap.get("out_refund_no")+"</out_refund_no>")
			.append("<out_trade_no>"+paramMap.get("out_trade_no")+"</out_trade_no>")
			.append("<refund_fee>"+paramMap.get("refund_fee")+"</refund_fee>")
			.append("<total_fee>"+paramMap.get("total_fee")+"</total_fee>")
			.append("<transaction_id></transaction_id>")
			.append("<sign>"+paramMap.get("sign")+"</sign>")
			.append("</xml> ");
		return xmlStr.toString();
    }
    
	public static String sendPost(String url,String xmlStr) throws UnsupportedEncodingException{
		String result = "";
		HttpPost httpPost = new HttpPost(url);
		//得指明使用UTF-8编码，否则到API服务器XML的中文不能被成功识别
		StringEntity postEntity = new StringEntity(xmlStr, "UTF-8");
		httpPost.addHeader("Content-Type", "text/xml");
		httpPost.setEntity(postEntity);

		//设置请求器的配置
		HttpClient httpClient = new DefaultHttpClient();
		try {
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(entity, "UTF-8");
		} catch (RuntimeException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		    httpPost.abort();
		}
		return result;
    }
	
    //解析统一下单返回数据
    public static Map<String,String> getPayUrlFromXml(String rs){
		Map<String,String> rsMap = new HashMap<String,String>();
		Document doc = null;
		try {
		    doc = DocumentHelper.parseText(rs);
		    Element rootElt = doc.getRootElement(); // 获取根节点
			if("SUCCESS".equals(rootElt.elementText("return_code"))){
				
				if ("SUCCESS".equals(rootElt.elementText("result_code"))) {
					rsMap.put("flag", "success");
					rsMap.put("url", rootElt.elementText("code_url"));
				} else {
					rsMap.put("flag", "fail");
					rsMap.put("msg", rootElt.elementText("err_code_des"));
				}
			} else{
				rsMap.put("flag", "fail");
				rsMap.put("msg", rootElt.elementText("return_msg"));
			}
		}
		catch (DocumentException e) {
		    e.printStackTrace();
		} // 将字符串转为XML
		return rsMap;
    }
    //解析支付结果返回数据
    public static Map<String,String[]> getPayResultFromXml(String rs){
        Map<String,String[]> map = new HashMap<String,String[]>();
        Document doc = null;
        try {
			doc = DocumentHelper.parseText(rs);
			StringBuilder str = new StringBuilder();
			Element rootElt = doc.getRootElement(); // 获取根节点
			rootElt.elementIterator();
			for(Iterator iter = rootElt.elementIterator(); iter.hasNext();){
				Element element= (Element)iter.next();
				map.put(element.getName(), new String[]{element.getStringValue()});
				if("handle".equals(element.getName())){
					continue;
				}
				if(!"sign".equals(element.getName())){
					if(iter.hasNext()){
						str = str.append(element.getName()+"="+element.getStringValue()+"&");
					} else{
						str = str.append(element.getName()+"="+element.getStringValue());
					}
				}
			}
			map.put("stringA", new String[]{str.toString()});
        } catch (DocumentException e) {
            e.printStackTrace();
        } // 将字符串转为XML
        return map;
    }
    /**    
     * getWeixinQueryXml  
     * @param ecOrgWeixin
     * @param logId
     * @return        
     * @return String    
     * @Exception 
    */
    public static String getWeixinQueryXml(String logId,String sign,String random,ConfigWechat configWechat) {
		StringBuilder xmlStr = new StringBuilder();
		xmlStr.append("<xml>")
			.append("<appid>"+configWechat.getAppIdGz()+"</appid>")
			.append("<mch_id>"+configWechat.getMchId()+"</mch_id>")
			.append("<nonce_str>"+random+"</nonce_str>")
			.append("<out_trade_no>"+logId+"</out_trade_no>")
			.append("<sign>"+sign+"</sign>")
			.append("</xml> ");
		return xmlStr.toString();
    }
	//解析支付结果返回数据
    public static Map<String,String> getQueryResultFromXml(String rs){
        Map<String,String> map = new HashMap<String,String>();
        Document doc = null;
        try {
			doc = DocumentHelper.parseText(rs);
			Element rootElt = doc.getRootElement(); // 获取根节点
			rootElt.elementIterator();
			for(Iterator iter = rootElt.elementIterator(); iter.hasNext();){
			   Element element= (Element)iter.next();
			   map.put(element.getName(), element.getStringValue());
			}
		} catch (DocumentException e) {
		    e.printStackTrace();
		} // 将字符串转为XML
        return map;
    }

	public static String sendPostForRefund(String url, String xmlStr) {
		try {
			String output = "";
			URL requestUrl = new URL(url);  
	        HttpsURLConnection connection = (HttpsURLConnection) requestUrl.openConnection();  
	        connection.setDoOutput(true);  
	        connection.setDoInput(true);  
	        connection.setUseCaches(false);  
	        connection.setRequestMethod(url);  
            OutputStream outputStream = connection.getOutputStream();  
            outputStream.write(output.getBytes("UTF-8"));  
            outputStream.close();  
	        // 从输入流读取返回内容  
	        InputStream inputStream = connection.getInputStream();  
	        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
	        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
	        String str = null;  
	        StringBuffer buffer = new StringBuffer();  
	        while ((str = bufferedReader.readLine()) != null) {  
	            buffer.append(str);  
	        }  
	        bufferedReader.close();  
	        inputStreamReader.close();  
	        inputStream.close();  
	        inputStream = null;  
	        connection.disconnect();  
	        return buffer.toString(); 
		} catch(Exception e) {
			e.printStackTrace();
		}
		return ""; 
	}
}
